//
//  ADJgCustomAdapterGDTNativeAd.m
//  ADJgCustomPlatform
//
//  Created by apple on 2025/1/6.
//

#import "ADJgCustomAdapterGDTNativeAd.h"
#import <GDTMobSDK/GDTNativeExpressAd.h>
#import "ADJgCustomAdapterGDTNativeAdView.h"

@interface ADJgCustomAdapterGDTNativeAd () <GDTNativeExpressAdDelegete>
{
    GDTNativeExpressAd *_nativeExpressAd;
    NSMapTable <UIView *, ADJgCustomAdapterGDTNativeAdView *> *_weakMapTable;
    ADJgCustomAdapterNativeRequestContext *_context;
    BOOL _isGdtBidding;
    GDTNativeExpressAdView *_expressAdView;
}

@end

@implementation ADJgCustomAdapterGDTNativeAd

// MARK: - Override

+ (void)load {
    [self registPlatformAdLoaderClass:self forSdkName:@"gdt" renderType:ADJgAdapterRenderTypeExpress];
}

- (instancetype)init{
    self = [super init];
    if(self){
        _weakMapTable = [NSMapTable weakToWeakObjectsMapTable];
    }
    return self;
}

- (void)requestAdWithContext:(ADJgCustomAdapterNativeRequestContext *)context {
    _context = context;
    _isGdtBidding = NO;
    [self requestNativeWithContext:context];
}

- (void)biddingRequestWithContext:(ADJgCustomAdapterNativeRequestContext *)context{
    _context = context;
    _isGdtBidding = YES;
    [self requestNativeWithContext:context];
}

- (void)requestNativeWithContext:(ADJgCustomAdapterNativeRequestContext *)context{
    if(!_nativeExpressAd) {
        _nativeExpressAd = [[GDTNativeExpressAd alloc] initWithPlacementId:context.posId adSize:context.adSize];
        _nativeExpressAd.delegate = self;
        _nativeExpressAd.videoMuted = context.muted;
    }
    [_nativeExpressAd loadAd:context.loadCount];
}

- (void)biddingResult:(ADJgSDKSourceBiddingResult)result AllPrice:(NSArray *)allPrices{
    // 获取一价二价
    NSNumber *winnerPrice = 0;
    NSNumber *secondPrice = 0;
    if (allPrices.count > 0) {
        NSNumber *firstPrice = allPrices.firstObject;
        // 聚合平台存储为单位为：分，GDT 是以元返回，同时也需要已元上报
        winnerPrice = [NSNumber numberWithFloat:firstPrice.floatValue * 100];
    }
    if (allPrices.count > 1) {
        NSNumber *tempSecondPrice = allPrices[1];
        secondPrice = [NSNumber numberWithFloat:tempSecondPrice.floatValue * 100];
    }
    switch (result) {
        case ADJgSDKSourceBiddingResult_Sucess:
            [self sendWinNotificationWithWinnerPrice:[NSNumber numberWithInteger:_expressAdView.eCPM] withSecondPrice:secondPrice];
            break;
        case ADJgSDKSourceBiddingResult_Failed:
            [self sendLossNotificationWithPrice:winnerPrice withRease:GDTAdBiddingLossReasonLowPrice withWinnerAdnID:@""];
            break;
        case ADJgSDKSourceBiddingResult_Timeout:
            [self sendLossNotificationWithPrice:@0 withRease:GDTAdBiddingLossReasonNoAd withWinnerAdnID:@""];
            break;
        default:
            [self sendLossNotificationWithPrice:@0 withRease:GDTAdBiddingLossReasonOther withWinnerAdnID:@""];
            break;
    }
}

/** 竞赢上报
 *  infoDic 字典类型，支持的key有
 *  GDT_M_W_E_COST_PRICE：竞胜价格 (单位: 分)，值类型为NSNumber *
 *  GDT_M_W_H_LOSS_PRICE：最高失败出价，值类型为NSNumber *
 */
- (void)sendWinNotificationWithWinnerPrice:(NSNumber *)winnerPrice withSecondPrice:(NSNumber *)secondPrice{
    if(winnerPrice == nil){
        return ;
    }
    
    NSMutableDictionary *infoDic = [NSMutableDictionary dictionary];
    
    [infoDic setValue:winnerPrice forKey:GDT_M_W_E_COST_PRICE];
    if (secondPrice != nil) {
        [infoDic setValue:secondPrice forKey:GDT_M_W_H_LOSS_PRICE];
    }else{
        [infoDic setValue:@(0) forKey:GDT_M_W_H_LOSS_PRICE];
    }
    [_expressAdView sendWinNotificationWithInfo:infoDic.copy];
}
/**
 *  竞败之后或未参竞调用
 *
 *  infoDic 竞败信息，字典类型，支持的key有
 *  GDT_M_L_WIN_PRICE ：竞胜价格 (单位: 分)，值类型为NSNumber *，选填
 *  GDT_M_L_LOSS_REASON ：优量汇广告竞败原因，竞败原因参考枚举GDTAdBiddingLossReason中的定义，值类型为NSNumber *，必填
 *  GDT_M_ADNID  ：竞胜方渠道ID，值类型为NSString *，必填
 */
- (void)sendLossNotificationWithPrice:(NSNumber *)price withRease:(GDTAdBiddingLossReason)reason withWinnerAdnID:(NSString *)winnerAdnID{
    NSMutableDictionary *infoDic = [NSMutableDictionary dictionary];
    [infoDic setValue:price forKey:GDT_M_L_WIN_PRICE];
    [infoDic setValue:@(reason) forKey:GDT_M_L_LOSS_REASON];
    [infoDic setValue:winnerAdnID forKey:GDT_M_ADNID];
    [_expressAdView sendLossNotificationWithInfo:infoDic.copy];
}

// MARK: - Helper

- (NSArray<ADJgCustomAdapterGDTNativeAdView *> *)creatNativeViewFrom:(NSArray<__kindof GDTNativeExpressAdView *> *)views {
    NSMutableArray *dataArray = [NSMutableArray new];
    for (GDTNativeExpressAdView *view in views) {
        view.controller = _context.viewController;
        ADJgCustomAdapterGDTNativeAdView *nativeView = [ADJgCustomAdapterGDTNativeAdView new];
        nativeView.gdtNativeAdView = view;
        [dataArray addObject:nativeView];
        [_weakMapTable setObject:nativeView forKey:view];
    }
    return dataArray.copy;
}

// MARK: - GDTNativeExpressAdDelegete

- (void)nativeExpressAdSuccessToLoad:(GDTNativeExpressAd *)nativeExpressAd views:(NSArray<__kindof GDTNativeExpressAdView *> *)views {
    NSInteger price = 0;
    if (_isGdtBidding) {
        _expressAdView = views.firstObject;
        price = _expressAdView.eCPM;
    }
    NSArray<ADJgCustomAdapterGDTNativeAdView *> *adViewArray = [self creatNativeViewFrom:views];
    [self trackNativeAdSucceedToLoadWithNativeAdViews:adViewArray ecpm:price/100.00];
}

- (void)nativeExpressAdFailToLoad:(GDTNativeExpressAd *)nativeExpressAd error:(NSError *)error {
    [self trackNativeAdFailToLoadWithError:error];
}

- (void)nativeExpressAdViewRenderSuccess:(GDTNativeExpressAdView *)nativeExpressAdView {
    ADJgCustomAdapterGDTNativeAdView *adView = [_weakMapTable objectForKey:nativeExpressAdView];
    adView.frame = nativeExpressAdView.bounds;
    [self trackNativeAdRenderSucceedWithNativeView:adView];
}

- (void)nativeExpressAdViewRenderFail:(GDTNativeExpressAdView *)nativeExpressAdView {
    ADJgCustomAdapterGDTNativeAdView *adView = [_weakMapTable objectForKey:nativeExpressAdView];
    [self trackNativeAdRenderFailedWithNativeView:adView];
}

- (void)nativeExpressAdViewExposure:(GDTNativeExpressAdView *)nativeExpressAdView {
    ADJgCustomAdapterGDTNativeAdView *adView = [_weakMapTable objectForKey:nativeExpressAdView];
    [self trackNativeAdExposuredWithNativeView:adView];
}

- (void)nativeExpressAdViewClicked:(GDTNativeExpressAdView *)nativeExpressAdView {
    ADJgCustomAdapterGDTNativeAdView *adView = [_weakMapTable objectForKey:nativeExpressAdView];
    [self trackNativeAdClickedWithNativeView:adView];
}

- (void)nativeExpressAdViewClosed:(GDTNativeExpressAdView *)nativeExpressAdView {
    ADJgCustomAdapterGDTNativeAdView *adView = [_weakMapTable objectForKey:nativeExpressAdView];
    [self trackNativeAdClosedWithNativeView:adView];
}

- (void)nativeExpressAdViewDidDismissScreen:(GDTNativeExpressAdView *)nativeExpressAdView {
    ADJgCustomAdapterGDTNativeAdView *adView = [_weakMapTable objectForKey:nativeExpressAdView];
    [self trackNativeAdLandingPageClosedWithNativeView:adView];
}

@end
